package com.xing.todolist.db.base;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

import com.xing.app.myutils.Utils.LogUtil;
import com.xing.todolist.db.dao.TodoMsgDao;

@Database(entities = {TodoMsg.class}, version = 2, exportSchema = false)
public abstract class AppDB extends RoomDatabase {

    private static AppDB instance;

    public static synchronized AppDB getInstance(Context context) {
        if (instance == null) {
            LogUtil.i("AppDB on create");
            instance = Room.databaseBuilder(context, AppDB.class, "todoList_db")
                    .addMigrations(MIGRATION_1_2)
                    .build();
            LogUtil.i("AppDB created");
        }
        return instance;
    }

    public abstract TodoMsgDao getTodoMsgDao();

    /**
     * 升级数据库的操作，从版本1到版本2需要新增或删除什么字段
     */
    static final Migration MIGRATION_1_2=new Migration(1,2) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            //没有布尔值，用INTEGER代替
            //使用"ALTER TABLE Word  ADD COLUMN bar_data2 INTEGER  NOT NULL DEFAULT 1"出错。
            //使用下面分开的形式,可以正确执行
            database.execSQL("ALTER TABLE TodoMsg "+" ADD COLUMN content text");
        }
    };

}
